function getWeekNumber(year) {
    var d = new Date(year, 0, 1);
    while (d.getDay() != 1) {
        d.setDate(d.getDate() + 1);
    }
    var to = new Date(year + 1, 0, 1);
    var i = 0;
    for (var from = d; from < to;) {
        from.setDate(from.getDate() + 6);
        if (from < to) {
            from.setDate(from.getDate() + 1);
        } else {
            to.setDate(to.getDate() - 1);
        }
        i++;
    }
    return i;
}
function getWeekNum(date) {
    var d = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
    var DoW = d.getDay();
    d.setDate(d.getDate() - (DoW + 6) % 7 + 3); // Nearest Thu
    var ms = d.valueOf(); // GMT
    d.setMonth(0);
    d.setDate(4); // Thu in Week 1
    return Math.round((ms - d.valueOf()) / (7 * 864e5)) + 1;
}

var currYear = new Date().getFullYear();
var data = {
    weekCount: getWeekNumber(currYear),
    currYear: currYear,
    loading: false,
    currSpuCode: 'M02',
    editWeek: getWeekNum(new Date()),

    spuList: [
        {spuCode: 'M02', spuName: '理想M02'},
        {spuCode: 'M01', spuName: '理想M01'}
    ],
    yearList: [
        {year: currYear},
        {year: currYear + 1},
        {year: currYear + 2}
    ],
    preYield: [],
    yield: [],
    preSale: [],
    sale: [],
    weekendStock: []
};

var app = new Vue({
    el: '#app',
    data: function () {
        return data;
    },
    methods: {
        onUploadExcel(){

        },
        onDownloadExcel (type) {
             type ="1"
            downloadForGet("/allotLong/export-allotlong-template/"+type, "");
        },
        //查询整车SPUlist
        querySPUList: function () {
            this.send('/allot/querySpuList', function (resultData) {
                if (resultData != "") {
                    data.spuList = resultData;
                    data.currSpuCode = resultData[0].spuCode;
                }
            });
        },

        //查询长线调拨
        queryAllotLongList: function () {
            if(data.currYear > new Date().getFullYear()) {
                this.editWeek = 1;
            } else {
                this.editWeek = getWeekNum(new Date());
            }
            var self = this;
            this.send('/allotLong/queryAllotLongList', {
                year:data.currYear,
                spuCode: data.currSpuCode
            }, function (resultData) {
                if (resultData) {
                    self.setData(resultData);
                    self.mergeData(data.yield);
                    self.mergeData(data.preYield);
                    self.mergeData(data.sale, data.preSale);
                    self.mergeData(data.weekendStock);

                }
                if(data.isInit !== undefined) {
                    $('#mainTable').fixedHeaderTable('destroy');
                } else {
                    data.isInit = true;
                }
                setTimeout(function () {
                    $('#mainTable').fixedHeaderTable({
                        altClass: 'odd',
                        fixedColumns: 3
                        // ,height:'500'
                    });
                }, 0);
            });
        },

        savePreYield: function () {
            for(var e of data.preYield) {
                e.year = data.currYear;
                e.spuCode = data.currSpuCode;
            }
            var self = this;
            this.sendJson('/allotLong/savePreYield', data.preYield, function (data) {
                self.queryAllotLongList();
                self.$message.success('保存成功');
            });

        },

        setData: function (resultData) {
            var type, firstItem;
            for(let list of resultData) {
                firstItem = list[0];
                if(!firstItem || firstItem.length == 0) continue;
                type = firstItem.stateType;
                if(1 == type) {
                    list = this.calYearListCount(list, false);
                    data.preYield = list;
                } else if (2 == type) {
                    list = this.calYearListCount(list, true);
                    data.yield = list;
                } else if(3 == type) {
                    list = this.calYearListCount(list, true);
                    data.sale = list;
                } else if(4 == type) {
                    var lastWeekStock = 0;
                    for(var i in list) {
                        lastWeekStock = list[i]['wk'+(data.editWeek-1)];
                        list[i].yearCount = lastWeekStock || 0;
                    }
                    data.weekendStock = list;
                } else if(5 == type) {
                    list = this.calYearListCount(list, false);
                    data.preSale = list;
                }
            }
        },

        mergeData: function (to, added) {
            for(var i in to) {
                if(!added) {
                    this.initData(to[i]);
                } else {
                    if(!added[i]) {
                        this.initData(to[i]);
                        continue;
                    }

                    to[i].yearCount = added[i].yearCount + to[i].yearCount;
                    this.mergeWeekRow(to[i], added[i]);
                }
            }
            return to;
        },
        mergeWeekRow: function (to, added) {
            var weekKey;
            for(var i=1;i<=data.weekCount; i++) {
                weekKey = 'wk'+i;
                if(i >= data.editWeek) {
                    to[weekKey] = added[weekKey] || 0;
                } else {
                    if(!to[weekKey]) to[weekKey] = 0;
                }
            }
            return to;
        },

        initData: function (row) {
            var weekKey;
            for(var i=1;i<=data.weekCount; i++) {
                weekKey = 'wk'+i;
                if(!row[weekKey]) row[weekKey] = 0;
            }
            return row;
        },

        calYearListCount: function (list, isReal) {
            for(var i in list) {
                list[i].yearCount = this.calYearCount(list[i], isReal);
            }
            return list;
        },
        calYearCount: function (item, isReal) {
            var yearCount = 0;
            var value;
            for(var i=1;i<=data.weekCount; i++) {
                value = item['wk'+i];
                if(value) {
                    if(isReal) {
                        if (i < data.editWeek) {
                            yearCount += value;
                        }
                    } else {
                        if (i >= data.editWeek) {
                            yearCount += value;
                        }
                    }
                }
            }

            return yearCount;
        },

        weekendStockRatio: function (index, key) {//库存系数
            var saleItem = data.sale[index];
            var stockItem = data.weekendStock[index];

            if(!saleItem || !stockItem) {
                return 0;
            }

            var saleNum = saleItem[key];
            var stockNum = stockItem[key];
            if(saleNum==undefined || stockItem==undefined || saleNum==0 || stockNum==0) {
                return 0;
            }

            var percent = stockNum/saleNum;
            percent = Math.round(percent * 1000)/1000;
            if(percent == 0) return 0;
            return percent.toFixed(3);
        },

        send: function (url, data, succ, error) {
            var _data = {};
            if(data === undefined) {
                data = succ, succ = error;
            } else {
                _data = data;
            }
            var self = this;
            $.ajax({
                url:  url,
                data: _data,
                type: "post",
                // dataType: "json",
                async: false,
                // contentType: "application/json;charset=UTF-8",
                success: succ,
                error: error || function (xhr, error, msg) {
                    self.$message.error('服务器异常');
                }
            });
        },
        sendJson: function (url, data, succ, error) {
            var _data = {};
            if(data === undefined) {
                data = succ, succ = error;
            } else {
                _data = data;
            }
            var self = this;
            $.ajax({
                url:  url,
                data: JSON.stringify(_data),
                type: "post",
                dataType: "json",
                async: false,
                contentType: "application/json;charset=UTF-8",
                success: succ,
                error: error || function (xhr, error, msg) {
                    self.$message.error('服务器异常');
                }
            });
        }
    },


    mounted: function () {
        this.loading = true;
        var tHeight = $(window).height() - 200;
        $('#mainTable').parent().css('height', tHeight);
        this.querySPUList();
        this.queryAllotLongList();
        this.loading = false;
    },
    computed: {
    }
})